package ${packagePrefix}.infrastructure.repository;

import ${packagePrefix}.client.dto.query.${domainObjectName}ListQry;
import ${packagePrefix}.domain.gateway.${domainObjectName}Repository;
import ${packagePrefix}.domain.model.${tableName?lower_case}.${domainObjectName};
import ${packagePrefix}.infrastructure.dataobject.${domainObjectName}DO;
import ${packagePrefix}.infrastructure.mapper.${domainObjectName}Mapper;
import ${packagePrefix}.infrastructure.converter.${domainObjectName}Converter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
<#if hasDateFields>
import java.util.Date;
</#if>

/**
 * ${entityComment}仓储实现
 */
@Repository
public class ${domainObjectName}RepositoryImpl implements ${domainObjectName}Repository {

    @Autowired
    private ${domainObjectName}Mapper ${domainObjectName?uncap_first}Mapper;
    
    @Autowired
    private ${domainObjectName}Converter ${domainObjectName?uncap_first}Converter;

    @Override
    public Optional<${domainObjectName}> findById(Long id) {
        ${domainObjectName}DO ${domainObjectName?uncap_first}DO = ${domainObjectName?uncap_first}Mapper.selectById(id);
        return Optional.ofNullable(${domainObjectName?uncap_first}DO)
                .map(${domainObjectName?uncap_first}Converter::toDomain);
    }

    @Override
    public Long save(${domainObjectName} ${domainObjectName?uncap_first}) {
        ${domainObjectName}DO ${domainObjectName?uncap_first}DO = ${domainObjectName?uncap_first}Converter.toDO(${domainObjectName?uncap_first});
        if (${domainObjectName?uncap_first}DO.getId() == null) {
            <#if hasDateFields>
            // 设置创建时间和更新时间
            Date now = new Date();
            ${domainObjectName?uncap_first}DO.setCreateTime(now);
            ${domainObjectName?uncap_first}DO.setUpdateTime(now);
            </#if>
            ${domainObjectName?uncap_first}Mapper.insert(${domainObjectName?uncap_first}DO);
        } else {
            <#if hasDateFields>
            // 设置更新时间
            ${domainObjectName?uncap_first}DO.setUpdateTime(new Date());
            </#if>
            ${domainObjectName?uncap_first}Mapper.updateById(${domainObjectName?uncap_first}DO);
        }
        return ${domainObjectName?uncap_first}DO.getId();
    }

    @Override
    public List<${domainObjectName}> findByCondition(${domainObjectName}ListQry qry) {
        List<${domainObjectName}DO> ${domainObjectName?uncap_first}DOList = ${domainObjectName?uncap_first}Mapper.selectByCondition(qry);
        return ${domainObjectName?uncap_first}DOList.stream()
                .map(${domainObjectName?uncap_first}Converter::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public void deleteById(Long id) {
        ${domainObjectName?uncap_first}Mapper.deleteById(id);
    }
} 